import request from '../../utils/request';
import useSwr from 'swr';
import { BlogPost } from '../../store';
import { MockApiService } from '../../utils/mockApi';

// 类型定义
export interface PostsParams {
  page?: number;
  pageSize?: number;
  search?: string;
  tag?: string;
  sortBy?: 'date' | 'views' | 'likes';
  order?: 'asc' | 'desc';
}

export interface PostsResponse {
  posts: BlogPost[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

// 判断是否使用模拟数据
const useMockData = process.env.NODE_ENV === 'development';

// API 函数
export async function getPosts(params?: PostsParams) {
  if (useMockData) {
    return await MockApiService.getPosts(params);
  }
  const { data } = await request.get<PostsResponse>('/posts', { params });
  return data;
}

// SWR Hooks
export default function usePosts(params?: PostsParams) {
  const queryString = params ? new URLSearchParams(params as any).toString() : '';
  const url = `/posts${queryString ? `?${queryString}` : ''}`;

  const { data = { posts: [], total: 0, page: 1, pageSize: 10, totalPages: 0 } } = useSwr(url, () =>
    getPosts(params),
  );

  return data;
}
